package com.compass.doctor.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.compass.doctor.R
import com.compass.framework.constant.LOGIN_FAILURE
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.LoginInformation
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.getStringFromResource
import com.compass.network.callback.IApiErrorCallback
import com.compass.network.flow.requestFlow
import com.compass.network.manager.ApiManager
import com.compass.network.viewmodel.BaseViewModel
import com.google.gson.JsonObject
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.auth.AuthService
import com.netease.nimlib.sdk.auth.ClientType
import com.netease.nimlib.sdk.auth.LoginInfo
import com.netease.nimlib.sdk.auth.OnlineClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**

 *
 * @desc   登录viewModel
 */
class LoginViewModel : BaseViewModel() {
    val loginLiveData = MutableLiveData<LoginInformation?>()
    val loginImLiveData = MutableLiveData<LoginInfo?>()
    val smsCodeLiveData = MutableLiveData<Boolean>()

    /**
     * 登录
     * @param mobile  用户手机号码
     * @param password  密码
     */
    fun login(mobile: String, password: String): LiveData<LoginInformation?> {
        val params = JsonObject().apply {
            addProperty("mobile", mobile)
            addProperty("code", password)
        }
        //通过flow来请求
        viewModelScope.launch(Dispatchers.Main) {
            val data = requestFlow(requestCall = {
                ApiManager.api.login(params)
            }, errorBlock = { _, error ->
                TipsToast.showTips(error)
                loginLiveData.value = null
            })
            loginLiveData.value = data
        }

        return loginLiveData
    }


    /**
     *获取登录验证码
     */
    fun geSmsCode(mobile: String) {
        val params = JsonObject().apply {
            addProperty("mobile", mobile)
            addProperty("scene", 1)
        }
        launchUIWithResult(responseBlock = {
            ApiManager.api.geSmsCode(params)
        }, errorCall = object : IApiErrorCallback {
            override fun onError(code: Int?, error: String?) {
                TipsToast.showTips(error)
                smsCodeLiveData.value=false
            }
        }, successBlock = {
            TipsToast.showTips("发送成功")
            smsCodeLiveData.value=true
        })

    }


    /**
     * 登录IM
     */
    fun loginIm(username: String?, token: String?): LiveData<LoginInfo?> {
        val loginInfo = LoginInfo(username, token, null, 0)
        val callback: RequestCallback<LoginInfo> = object : RequestCallback<LoginInfo> {
            override fun onSuccess(info: LoginInfo?) {
                UserInfoManager.saveImUserAccount(username)
                UserInfoManager.saveImToken(token)
                loginImLiveData.value = info
            }

            override fun onFailed(code: Int) {
                //清理登录账号、token缓存，调用login失败后，不允许走自动登录。
                UserInfoManager.clearUserInfo()
                if (code == 302) {
                    TipsToast.showTips(getStringFromResource(R.string.login_password_error))
                } else {
                    TipsToast.showTips(getStringFromResource(R.string.login_error))
                    LogUtil.d(getStringFromResource(R.string.login_error) + "code==$code")
                }
                loginImLiveData.value = null
            }

            override fun onException(exception: Throwable) {
                //清理登录账号、token缓存，调用login失败后，不允许走自动登录。
                UserInfoManager.clearUserInfo()
                TipsToast.showTips(getStringFromResource(R.string.login_error) + exception.message)
            }
        }
        NIMClient.getService(AuthService::class.java).login(loginInfo).setCallback(callback)

        return loginImLiveData
    }

//    private val otherClientsObserver = Observer< List<OnlineClient>>() { onlineClients ->
//        if(onlineClients == null || onlineClients.isEmpty()){
//            return@Observer
//        }
//        val onlineClient = onlineClients[0]
//        for (client in onlineClients){
//            LogUtil.d("登录的设备数据是")
//            LogUtil.d("ip = ${client.clientIp} , type = ${client.clientType}," +
//                    " os = ${client.os} , customType = ${client.customClientType}, ")
//        }
//
//        //只需要处理安卓和ios上登录的情况
//        when(onlineClient.clientType){
//            ClientType.Windows->{
//                LogUtil.d("other client is windows login")
//            }
//            ClientType.iOS->{
////                LogUtil.d("other client is ios login")
//                showToast("账号已在其他端登录")
//                //退出云信账号
//                LiveDataBus.get().with(LOGIN_FAILURE).postValue(LOGIN_FAILURE)
//            }
//            ClientType.Android->{
//                showToast("账号已在其他端登录")
//                //退出云信账号
//                LiveDataBus.get().with(LOGIN_FAILURE).postValue(LOGIN_FAILURE)
////                kickOtherClient(onlineClient)
//                LogUtil.d("other client is android login")
//            }
//        }
//    }
    /**
     * 将其它客户端踢下线
     */
//    private fun kickOtherClient(onlineClient:OnlineClient){
//        NIMClient.getService(AuthService::class.java).kickOtherClient(onlineClient).setCallback(object :RequestCallback<Void>{
//            override fun onSuccess(result: Void?) {
//                LogUtil.d("other devices are successfully kicked. ")
//            }
//
//            override fun onFailed(code: Int) {
//                LogUtil.d("other devices are failed kicked. ")
//                LogUtil.d("failed：code $code ")
//            }
//
//            override fun onException(exception: Throwable?) {
//                LogUtil.d("other devices are exception kicked. ")
//            }
//
//        })
//    }

}